package com.hmdp.redis;

import com.hmdp.entity.Shop;
import com.hmdp.service.IShopService;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.SHOP_GEO_KEY;

/**
 * @author xiaoli
 * @date 2023/1/17
 */
@Slf4j
@SpringBootTest
public class InitData {

    @Resource
    public IShopService shopService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 将商铺信息写入redis，这里我们直接在测试类中将信息写入。
     */
    @Test
    public void loadDataToRedis() {
        // 获取所有商家信息
        List<Shop> shopList = shopService.list();
        // 按照商家类型分组
        Map<Long, List<Shop>> map = shopList.stream().collect(Collectors.groupingBy(Shop::getTypeId));
        // 遍历所有商家 将商家添加到redis中
        for (Map.Entry<Long, List<Shop>> entry : map.entrySet()) {
            //商家类型ID
            Long typeId = entry.getKey();
            String key = SHOP_GEO_KEY + typeId;
            List<Shop> list = entry.getValue();
            // 这里面的那个泛型指的是geo里面保存的那个member的值的类型 这里我们保存的是shopId
            List<RedisGeoCommands.GeoLocation<String>> locations = new ArrayList<>(list.size());
            // 遍历当前typeId的所有商铺信息
            for (Shop shop : list) {
                RedisGeoCommands.GeoLocation<String> geoLocation = new RedisGeoCommands.GeoLocation<>(
                        shop.getId().toString(),
                        new Point(shop.getX(), shop.getY())
                );
                locations.add(geoLocation);
            }
            stringRedisTemplate.opsForGeo().add(key, locations);
        }
    }
}
